// Uni-app API 模拟（用于在标准浏览器环境中运行）

// 模拟系统信息
const mockSystemInfo = {
  system: navigator.platform || 'Web',
  platform: 'h5',
  version: navigator.appVersion,
  brand: 'Web',
  model: 'Browser',
  pixelRatio: window.devicePixelRatio || 1,
  screenWidth: window.screen.width,
  screenHeight: window.screen.height,
  windowWidth: window.innerWidth,
  windowHeight: window.innerHeight,
  statusBarHeight: 0
}

// 模拟uni对象
export const uni = {
  // 系统信息
  getSystemInfoSync: () => mockSystemInfo,

  // 存储相关
  getStorageSync: (key: string) => {
    try {
      return JSON.parse(localStorage.getItem(key) || '')
    } catch {
      return localStorage.getItem(key) || ''
    }
  },

  setStorageSync: (key: string, value: any) => {
    try {
      localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value))
    } catch (error) {
      console.error('存储失败:', error)
    }
  },

  removeStorageSync: (key: string) => {
    localStorage.removeItem(key)
  },

  // 剪贴板
  setClipboardData: ({ data, success, fail }: {
    data: string
    success?: () => void
    fail?: (error: any) => void
  }) => {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(data)
        .then(() => success?.())
        .catch((error) => fail?.(error))
    } else {
      // 降级方案
      const textarea = document.createElement('textarea')
      textarea.value = data
      document.body.appendChild(textarea)
      textarea.select()
      try {
        document.execCommand('copy')
        success?.()
      } catch (error) {
        fail?.(error)
      }
      document.body.removeChild(textarea)
    }
  },

  // 提示相关
  showToast: ({ title, icon = 'none', duration = 1500 }: {
    title: string
    icon?: 'success' | 'error' | 'loading' | 'none'
    duration?: number
  }) => {
    console.log(`Toast: ${title} (${icon})`)
    // 这里可以实现一个简单的toast组件
    alert(title)
  },

  showLoading: ({ title = '加载中...', mask = true }: {
    title?: string
    mask?: boolean
  } = {}) => {
    console.log(`Loading: ${title}`)
  },

  hideLoading: () => {
    console.log('Hide loading')
  },

  showModal: ({ title, content = '', success, fail }: {
    title: string
    content?: string
    success?: (res: { confirm: boolean; cancel: boolean }) => void
    fail?: () => void
  }) => {
    const result = confirm(`${title}\n${content}`)
    success?.({ confirm: result, cancel: !result })
  },

  // 导航相关
  navigateTo: ({ url }: { url: string }) => {
    console.log(`Navigate to: ${url}`)
    // 这里可以实现路由跳转
  },

  redirectTo: ({ url }: { url: string }) => {
    console.log(`Redirect to: ${url}`)
  },

  reLaunch: ({ url }: { url: string }) => {
    console.log(`ReLaunch to: ${url}`)
  },

  // 登录相关（模拟）
  login: ({ provider, success, fail }: {
    provider: string
    success?: (res: { code: string }) => void
    fail?: (error: any) => void
  }) => {
    console.log(`Login with: ${provider}`)
    // 模拟登录成功
    setTimeout(() => {
      success?.({ code: 'mock_code_' + Date.now() })
    }, 1000)
  },

  getUserProfile: ({ desc, success, fail }: {
    desc: string
    success?: (res: { userInfo: any }) => void
    fail?: () => void
  }) => {
    console.log(`Get user profile: ${desc}`)
    // 模拟用户信息
    setTimeout(() => {
      success?.({
        userInfo: {
          nickName: '测试用户',
          avatarUrl: '',
          gender: 0,
          country: '中国',
          province: '北京',
          city: '北京'
        }
      })
    }, 500)
  },

  // 生物识别相关（模拟）
  checkIsSupportSoterAuthentication: ({ success, fail }: {
    success?: (res: { supportMode: string[] }) => void
    fail?: () => void
  }) => {
    // 模拟支持指纹识别
    success?.({ supportMode: ['fingerPrint'] })
  },

  startSoterAuthentication: ({ requestAuthModes, challenge, authContent, success, fail }: {
    requestAuthModes: string[]
    challenge: string
    authContent: string
    success?: () => void
    fail?: (error: any) => void
  }) => {
    const result = confirm(`${authContent}\n是否允许生物识别？`)
    if (result) {
      success?.()
    } else {
      fail?.({ errMsg: '用户取消' })
    }
  },

  // 振动
  vibrateShort: ({}: {}) => {
    console.log('Vibrate short')
  },

  vibrateLong: ({}: {}) => {
    console.log('Vibrate long')
  }
}

// 支付宝相关模拟
export const my = {
  getAuthCode: ({ scopes, success, fail }: {
    scopes: string[]
    success?: (res: { authCode: string }) => void
    fail?: (error: any) => void
  }) => {
    console.log('Alipay getAuthCode')
    setTimeout(() => {
      success?.({ authCode: 'mock_auth_code_' + Date.now() })
    }, 1000)
  },

  getOpenUserInfo: ({ success, fail }: {
    success?: (res: { response: string }) => void
    fail?: () => void
  }) => {
    console.log('Alipay getOpenUserInfo')
    setTimeout(() => {
      success?.({
        response: JSON.stringify({
          nickName: '支付宝用户',
          avatar: ''
        })
      })
    }, 500)
  },

  ap: {
    faceVerify: ({ bizType, bizId, success, fail }: {
      bizType: string
      bizId: string
      success?: () => void
      fail?: (error: any) => void
    }) => {
      const result = confirm('支付宝人脸识别\n是否允许？')
      if (result) {
        success?.()
      } else {
        fail?.({ errorMessage: '用户取消' })
      }
    }
  }
}

// 抖音相关模拟
export const tt = {
  login: ({ success, fail }: {
    success?: (res: { code: string }) => void
    fail?: (error: any) => void
  }) => {
    console.log('TikTok login')
    setTimeout(() => {
      success?.({ code: 'mock_douyin_code_' + Date.now() })
    }, 1000)
  },

  getUserInfo: ({ success, fail }: {
    success?: (res: { userInfo: any }) => void
    fail?: () => void
  }) => {
    console.log('TikTok getUserInfo')
    setTimeout(() => {
      success?.({
        userInfo: {
          nickName: '抖音用户',
          avatarUrl: ''
        }
      })
    }, 500)
  }
}

// 全局声明
declare global {
  interface Window {
    uni: typeof uni
    my: typeof my
    tt: typeof tt
  }
}

// 挂载到全局
if (typeof window !== 'undefined') {
  window.uni = uni
  window.my = my
  window.tt = tt
}